<template>
	<div class="echarts" :id="id"></div>
</template>

<script>
	export default {
		name:'echarts',
		props: {
			options: {
				type: Object,
				default: () => ({}),
			},
		},
		watch:{
			option:{
				deep:true,
				handler(val){
					this.$emit('update:options',val);
				}
			},
			options:{
				deep:true,
				immediate:true,
				handler(val){
					this.option = val;
				}
			}
		},
		data(){
			return {
				id:null,
				chart:null,
				option:{},
			}
		},
		created() {
			this.id = this.UUID();	
		},
		mounted() {
			this.initEchart();
			window.addEventListener('resize', this.eventListener);
		},
		beforeDestroy(){
			window.removeEventListener('resize', this.eventListener);
		},
		methods:{
			//initEchart
			initEchart(){
				if (!this.chart) {
					const dom = document.getElementById(this.id);
					this.chart = this.$echarts.init(dom);
				} else {
					return;
				}
				if (!this.option) return;
				this.chart.setOption(this.option);
			},
			//监听自适应echart
			eventListener () {
				if (this.chart) {
					this.chart.resize();
				}
			},
			//UUID
			UUID () {
			  var d = new Date().getTime();
			  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			      var r = (d + Math.random()*16)%16 | 0;
			      d = Math.floor(d/16);
			      return (c=='x' ? r : (r&0x7|0x8)).toString(16);
			  });
			  return uuid;
			}
		}
	}
</script>

<style>
	.echarts {
		width: 100%;
		height: 100%;
	}
</style>
